package com.hfi.restful.web.controller;

import com.hfi.restful.dto.FileInfo;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author ChangLiang
 * @date 2019/7/31
 */
@RestController
@RequestMapping("/file")
public class FileController {

    private String folder = "D:\\03_project\\develop_IJ\\jpaDemo\\src\\main\\java\\com\\hfi\\restful\\web";

    /**
     * 文件上传
     * @param file
     * @return 后端返回上传文件的路径
     * @throws Exception
     */
    @PostMapping
    public FileInfo upload(MultipartFile file) throws Exception {

        System.out.println(file.getName());
        System.out.println(file.getOriginalFilename());
        System.out.println(file.getSize());

        File localFile = new File(folder, System.currentTimeMillis() + ".txt");

        file.transferTo(localFile);
        String absolutePath = localFile.getAbsolutePath();
        return new FileInfo(absolutePath);
    }

    @GetMapping("/{id}")
    public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        try (InputStream inputStream = new FileInputStream(new File(folder, id + ".txt"));
             OutputStream outputStream = response.getOutputStream()
        ) {
            response.setContentType("application/x-download");
            response.setHeader("Content-Disposition", "attachment;filename=test.txt");
            // 把文件的输入流 copy 到输出流中
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
        }
    }
}
